using System;
using QAssetBundle;
using UnityEngine;
using QFramework;

namespace ProjectSurvivor
{
	public partial class Player : ViewController
	{
		public float MovementSpeed = 5f;
		public static Player Default;
		private AudioPlayer mWalkSfx = null;

		private void Awake()
		{
			Default = this;
		}

		void Start()
		{
			
			ResKit.Init();
			
			// 与敌人发生碰撞
			HurtBox.OnTriggerEnter2DEvent(collider2D =>
			{
				HitHurtBox hitHurtBox = collider2D.GetComponent<HitHurtBox>();
				
				if (hitHurtBox && hitHurtBox.Owner.CompareTag("Enemy"))
				{
					Global.HP.Value--;
					
					if (Global.HP.Value <= 0)
					{
						this.DestroyGameObjGracefully();
						UIKit.OpenPanel<UIGameOverPanel>();
						AudioKit.PlaySound(Sfx.DIE);
					}
					else
					{
						AudioKit.PlaySound(Sfx.HURT);
					}
				}
			}).UnRegisterWhenGameObjectDestroyed(gameObject);
			
			// 更新血条
			void UpdateHP()
			{
				HpValue.fillAmount= Global.HP.Value / (float)Global.MaxHP.Value;
			}
			
			// 血量条发生变化
			Global.HP.RegisterWithInitValue(hp =>
			{
				UpdateHP();
			}).UnRegisterWhenGameObjectDestroyed(gameObject);
			Global.MaxHP.RegisterWithInitValue(maxHp =>
			{
				UpdateHP();
			}).UnRegisterWhenGameObjectDestroyed(gameObject);
		}

		private bool mFaceRight = true;
		
		private void Update()
		{
			float horizontal = Input.GetAxisRaw("Horizontal");
			float vertical = Input.GetAxisRaw("Vertical");

			if (Mathf.Abs(vertical) <= 0.01 && Mathf.Abs(horizontal) <= 0.01)
			{
				if (mFaceRight)
				{
					Sprite.Play("PlayerIdleRight");
				}
				else
				{
					Sprite.Play("PlayerIdleLeft");
				}

				if (mWalkSfx is not null)
				{
					mWalkSfx.Stop();
					mWalkSfx = null;
				}
			}
			else
			{
				if (horizontal > 0.01)
				{
					mFaceRight = true;
				}
				else if(horizontal < -0.01)
				{
					mFaceRight = false;
				}

				if (mWalkSfx is null)
				{
					mWalkSfx = AudioKit.PlaySound(Sfx.WALK, true);
				}
				
				if (mFaceRight)
				{
					Sprite.Play("PlayerWalkRight");
				}
				else
				{
					Sprite.Play("PlayerWalkLeft");
				}
			}

			Vector2 targetVelocity = new Vector2(horizontal, vertical).normalized * (MovementSpeed * Global.MovementSpeedRate.Value);
			
			SelfRigidbody2D.velocity = Vector2.Lerp(SelfRigidbody2D.velocity, targetVelocity, 1f - Mathf.Exp(-Time.deltaTime * 5)) ;
		}

		private void OnDestroy()
		{
			Default = null;
		}
	}
}
